module dgl.graphics.Texture2D;

import tango.stdc.stringz;

import derelict.sdl.video;
import derelict.sdl.image;
import derelict.sdl.sdl;

import derelict.opengl.gl;

import dgl.GameWindow;
import dgl.Vector2;

class Texture2D
{
	private uint m_width;
	
	private uint m_height;
	
	private GLuint m_id;
	
	public uint width()
	{
		return m_width;
	}
	
	public uint height()
	{
		return m_height;
	}
	
	package GLuint id()
	{
		return m_id;
	}
	
	public this()
	{
		m_id = 0;
		m_width = 0;
		m_height = 0;
	}
	
	public static Texture2D loadFromFile( char[] filename )
	{
		Texture2D ret = new Texture2D();

		SDL_Surface * surface = IMG_Load( toStringz( filename ) );

		if( ! surface )
			return null;
		
		ret.m_width = surface.w;
		ret.m_height = surface.h;

		glGenTextures( 1, &ret.m_id );

		GLenum format;
		uint nOfColors = surface.format.BytesPerPixel;
		if( nOfColors == 4 )
		{
			if( surface.format.Rmask == 0x000000ff )
				format = GL_RGBA;
			else
				format = GL_BGRA;
		}
		else if( nOfColors == 3 )
		{
			if( surface.format.Rmask == 0x000000ff )
				format = GL_RGB;
			else
				format = GL_BGR;
		}

		glBindTexture( GL_TEXTURE_2D, ret.m_id );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, ret.m_width, ret.m_height, 0, format,
				GL_UNSIGNED_BYTE, surface.pixels );
		
		return ret;
	}
}